﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.IO;
using System.Windows;

using Caliburn.Micro;
using GTServices.Entities;

namespace GTServices.Model.CoRoutine
{
    public class GetFileInfosFromDirectoryRoutine : IResult
    {
        public event EventHandler<ResultCompletionEventArgs> Completed;

        public bool Recurse { get; set; }
        public List<FileExtension> FileExtensions { get; set; }
        public string RootDirectory { get; set; }

        public List<Entities.FileInfo> Results { get; set; }


        public GetFileInfosFromDirectoryRoutine(string rootDir, bool recurse = true)
        {
            this.RootDirectory = rootDir;
            this.Recurse = recurse;
        }

        public void Execute(ActionExecutionContext context)
        {
            List<Entities.FileInfo> infos = new List<Entities.FileInfo>();

            try
            {

                var knownExtensions = GTApplication.Instance.DataModel.FileExtensions.ToList();

                String[] files = Directory.GetFiles(RootDirectory, "*", SearchOption.AllDirectories);


                foreach (String file in files)
                {
                    if (!File.Exists(file)) //SKipping directories
                        continue;

                    string fullPath = file;
                    string fileName = Path.GetFileName(file);

                    string path = Path.GetDirectoryName(file);
                    string ext = Path.GetExtension(file);
                    Entities.FileInfo fi = new Entities.FileInfo();
                    fi.Name = fileName;
                    fi.Path = path;
                    //fi.FullName = fullPath;
                    FileExtension fe = knownExtensions.FirstOrDefault((x) => x.Extension.Equals(ext, StringComparison.OrdinalIgnoreCase));

                    if (fe != null)
                    {
                        fi.FileExtension = fe;
                    }
                    else
                    {
                        fi.FileExtension = new FileExtension() { Extension = ext.ToLower() };
                        knownExtensions.Add(fi.FileExtension);
                    }
                    infos.Add(fi);
                }
            }
            catch (Exception e)
            {
                throw e; 
            }

            this.Results = infos;
            if(this.Completed != null)
                this.Completed(this, new ResultCompletionEventArgs()); 
        } 
    }
}
